/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.net.SocketException;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.Korisnik;
import model.Paket;
import model.Radnik;

/**
 *
 * @author Dejan
 */
public class KlijentHook extends Thread {
    private ObjectInputStream in;
    private int k;
    private Server serv;
    private Socket s;
    private String ime;

    KlijentHook(Socket s, Server serv, int id) {
        this.s=s;
       this.k=id;
        this.serv=serv;
        //
    }



    @Override
    public void run(){
    while(s.isConnected()){
            try {
                in = new ObjectInputStream(s.getInputStream());

                   otpakuj( (Paket)in.readObject());

            }   catch(SocketException ex){
            System.out.println("veza je prekinuta");
                break;
            
            }

            catch (IOException ex) {
                Logger.getLogger(KlijentHook.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
                    Logger.getLogger(KlijentHook.class.getName()).log(Level.SEVERE, null, ex);

            } 


        }
    
    }
void otpakuj(Paket paket) {

        if(paket.getProtokol().equals("login")){
           try {
            if (!serv.proveri(paket.getUser(), paket.getPass()))
            {
                s.close();} 
                else{
                   
                    System.out.println("klijent " + paket.getUser() + " se povezao");
                    //sf.setJtaOutputText("klijent " + paket.getUser() + " se povezao");
                   Paket p = new Paket("login OK");

                    serv.posalji(p,s);
                    }
                } catch (IOException ex) {
                Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
            }


        }
        if(paket.getProtokol().equals("zahtev nove sifre")){
                
               Paket p =new Paket("sifra radnika");
               p.setTovar(serv.dajSifru());
                serv.posalji(p,s);
        }
        if(paket.getProtokol().equals("unos radnika")){
                serv.unesiRadnika((Radnik) paket.getTovar());
               Paket p =new Paket("unos OK");
                serv.posalji(p,s);


        }
        if(paket.getProtokol().equals("zahtev liste radnika")){

                Paket p=new Paket("lista radnika");
                p.setTovar((Object) serv.prikaziRadnike());
                serv.posalji(p,s);
        }
    }

    /**
     * @return the k
     */
    public int getK() {
        return k;
    }

    /**
     * @param k the k to set
     */
    public void setK(int k) {
        this.k = k;
    }



}
